package com.sk.skplanet.commute.actions;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.location.Location;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.sk.skplanet.commute.R;
import com.sk.skplanet.commute.controllers.SeoulBusApiController;
import com.sk.skplanet.commute.daofactory.LocalDaoFactory;
import com.sk.skplanet.commute.layouts.DialogLayout;
import com.sk.skplanet.commute.vo.Data;
import com.sk.skplanet.commute.vo.Point;
import com.sk.skplanet.commute.vo.Route;
import com.sk.skplanet.commute.vo.StopInfo;
import com.skp.Tmap.TMapMarkerItem;
import com.skp.Tmap.TMapPOIItem;
import com.skp.Tmap.TMapPoint;
import com.skp.Tmap.TMapView;

public class API_searchTmap extends AsyncTask<String, Integer, String> {
	private Context context;
	private TMapView mMapView;

	double mLongitude = 126.93005708733297;
	double mLatitude = 37.6100156015977;

	@Deprecated
	public API_searchTmap(final Context context, TMapView mMapView, final AlertDialog ad, final int routePostion,
			final int pointPosition, final LinearLayout layout_dialog_stopinfo, final ScrollView scrollView,
			final LinearLayout layout_dialog_title) {
		this.context = context;
		this.mMapView = mMapView;

		mMapView.setOnClickListenerCallBack(new TMapView.OnClickListenerCallback() {

			@Override
			public boolean onPressUpEvent(ArrayList<TMapMarkerItem> markerlist, ArrayList<TMapPOIItem> poilist,
					TMapPoint point, PointF pointf) {

				return false;
			}

			@Override
			public boolean onPressEvent(ArrayList<TMapMarkerItem> markerlist, ArrayList<TMapPOIItem> poilist,
					TMapPoint point, PointF pointf) {
				final Route route = Data.memberData.getRoutes().get(routePostion);
				final Point pointData = route.getPoints().get(pointPosition);

				if (markerlist.size() == 1) {
					final String stationNameKor = markerlist.get(0).getCalloutTitle();
					final String stationId = markerlist.get(0).getCalloutSubTitle();

					if (pointData.getStopInfos() == null) pointData.setStopInfos(new ArrayList<StopInfo>());
					StopInfo stopinfo = new StopInfo(pointData.getStopInfos().size() + 1, stationId, stationNameKor,
							"", "", pointData.getId());

					new API_searchBus(context, routePostion, pointPosition, stopinfo).execute("getRouteByStation",
							stationId); // 호출 함수 이름, 호출 함수 인자
					// (1:공항, 3:간선, 4:지선, 5:순환, 6:광역, 7:인천, 8:경기, 9:폐지, 0:공용)
					ad.dismiss();
				} else if (markerlist.size() > 1) {
					((LinearLayout) scrollView.getChildAt(0)).removeAllViews();
					if (layout_dialog_title.getTag() == Data.DIALOG_MAP) {
						layout_dialog_title.setTag(Data.DIALOG_LIST);
						layout_dialog_title.getChildAt(2).setBackgroundResource(android.R.drawable.ic_dialog_map);
						layout_dialog_stopinfo.removeViewAt(layout_dialog_stopinfo.getChildCount() - 1);
						layout_dialog_stopinfo.addView(scrollView);
					}
					for (int i = 0; i < markerlist.size(); i++) {
						final String stationNameKor = markerlist.get(i).getCalloutTitle();
						final String stationId = markerlist.get(i).getCalloutSubTitle();
						{
							// 뷰 레이아웃 추가
							LinearLayout layout_station = DialogLayout.createDialogViewLayout(context, ad, point,
									stationNameKor, stationId, Data.DIALOG_STATION);
							if (layout_dialog_title.getTag() == Data.DIALOG_LIST) {
								layout_station.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										if (pointData.getStopInfos() == null) pointData
												.setStopInfos(new ArrayList<StopInfo>());
										StopInfo stopinfo = new StopInfo(pointData.getStopInfos().size() + 1,
												stationId, stationNameKor, "", "", pointData.getId());

										new API_searchBus(context, routePostion, pointPosition, stopinfo).execute(
												"getRouteByStation", stationId); // 호출 함수 이름, 호출 함수 인자
										// (1:공항, 3:간선, 4:지선, 5:순환, 6:광역, 7:인천, 8:경기, 9:폐지, 0:공용)
										ad.dismiss();
									}
								});
							}

							((LinearLayout) scrollView.getChildAt(0)).addView(layout_station);
						}

					}
				}

				return false;
			}

		});

		mMapView.setOnLongClickListenerCallback(new TMapView.OnLongClickListenerCallback() {

			@Override
			public void onLongPressEvent(ArrayList<TMapMarkerItem> markerlist, ArrayList<TMapPOIItem> poilist,
					TMapPoint point) {
			}
		});

		mMapView.setOnCalloutRightButtonClickListener(new TMapView.OnCalloutRightButtonClickCallback() {

			@Override
			public void onCalloutRightButton(TMapMarkerItem markerItem) {

				String strMessage = "";
				strMessage = "ID: " + markerItem.getID() + " " + "Title " + markerItem.getCalloutTitle();

			}
		});

	}

	public API_searchTmap(final Context context, TMapView mMapView, final AlertDialog ad, final int pointId, final LinearLayout layout_dialog_stopinfo, final ScrollView scrollView,
			final LinearLayout layout_dialog_title) {
		this.context = context;
		this.mMapView = mMapView;

		mMapView.setOnClickListenerCallBack(new TMapView.OnClickListenerCallback() {

			@Override
			public boolean onPressUpEvent(ArrayList<TMapMarkerItem> markerlist, ArrayList<TMapPOIItem> poilist,
					TMapPoint point, PointF pointf) {

				return false;
			}

			@Override
			public boolean onPressEvent(ArrayList<TMapMarkerItem> markerlist, ArrayList<TMapPOIItem> poilist,
					TMapPoint point, PointF pointf) {
				
				final Point pointData = LocalDaoFactory.getPoint(pointId);

				if (markerlist.size() == 1) {
					final String stationNameKor = markerlist.get(0).getCalloutTitle();
					final String stationId = markerlist.get(0).getCalloutSubTitle();

					if (pointData.getStopInfos() == null) pointData.setStopInfos(new ArrayList<StopInfo>());
					StopInfo stopinfo = new StopInfo(pointData.getStopInfos().size() + 1, stationId, stationNameKor,
							"", "", "", pointData.getId());

					new API_searchBus(context, pointId, stopinfo).execute("getRouteByStation",
							stationId); // 호출 함수 이름, 호출 함수 인자
					// (1:공항, 3:간선, 4:지선, 5:순환, 6:광역, 7:인천, 8:경기, 9:폐지, 0:공용)
					ad.dismiss();
				} else if (markerlist.size() > 1) {
					((LinearLayout) scrollView.getChildAt(0)).removeAllViews();
					if (layout_dialog_title.getTag() == Data.DIALOG_MAP) {
						layout_dialog_title.setTag(Data.DIALOG_LIST);
						layout_dialog_title.getChildAt(2).setBackgroundResource(android.R.drawable.ic_dialog_map);
						layout_dialog_stopinfo.removeViewAt(layout_dialog_stopinfo.getChildCount() - 1);
						layout_dialog_stopinfo.addView(scrollView);
					}
					for (int i = 0; i < markerlist.size(); i++) {
						final String stationNameKor = markerlist.get(i).getCalloutTitle();
						final String stationId = markerlist.get(i).getCalloutSubTitle();
						{
							// 뷰 레이아웃 추가
							LinearLayout layout_station = DialogLayout.createDialogViewLayout(context, ad, point,
									stationNameKor, stationId, Data.DIALOG_STATION);
							if (layout_dialog_title.getTag() == Data.DIALOG_LIST) {
								layout_station.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										if (pointData.getStopInfos() == null) pointData
												.setStopInfos(new ArrayList<StopInfo>());
										StopInfo stopinfo = new StopInfo(pointData.getStopInfos().size() + 1,
												stationId, stationNameKor, "", "", "", pointData.getId());

										new API_searchBus(context, pointId, stopinfo).execute(
												"getRouteByStation", stationId); // 호출 함수 이름, 호출 함수 인자
										// (1:공항, 3:간선, 4:지선, 5:순환, 6:광역, 7:인천, 8:경기, 9:폐지, 0:공용)
										ad.dismiss();
									}
								});
							}

							((LinearLayout) scrollView.getChildAt(0)).addView(layout_station);
						}

					}
				}

				return false;
			}

		});

		mMapView.setOnLongClickListenerCallback(new TMapView.OnLongClickListenerCallback() {

			@Override
			public void onLongPressEvent(ArrayList<TMapMarkerItem> markerlist, ArrayList<TMapPOIItem> poilist,
					TMapPoint point) {
			}
		});

		mMapView.setOnCalloutRightButtonClickListener(new TMapView.OnCalloutRightButtonClickCallback() {

			@Override
			public void onCalloutRightButton(TMapMarkerItem markerItem) {

				String strMessage = "";
				strMessage = "ID: " + markerItem.getID() + " " + "Title " + markerItem.getCalloutTitle();

			}
		});

	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);

		try {
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser = parserCreator.newPullParser();

			parser.setInput(new StringReader(result));
			parser.next();

			int parserEvent = parser.getEventType();
			if (mMapView.getTag() != null) {
				for (int ptr = 0; ptr < (Integer) mMapView.getTag(); ptr++) {
					mMapView.removeMarkerItem(Integer.toString(ptr));
				}
			}
			mMapView.setTag(0);

			String tagName = "";

			String tmparsId = "";
			String tmpstNm = "";
			double tmpLongitude = 0;
			double tmpLatitude = 0;

			double minLongitude = 9999;
			double minLatitude = 9999;
			double maxLongitude = 0;
			double maxLatitude = 0;

			while (parserEvent != XmlPullParser.END_DOCUMENT) {

				switch (parserEvent) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					tagName = parser.getName();
					break;
				case XmlPullParser.END_TAG:
					break;
				case XmlPullParser.TEXT:
					if ("arsId".equals(tagName)) {
						tmparsId = parser.getText();
					}
					if ("stNm".equals(tagName)) {
						tmpstNm = parser.getText();
					}
					if ("tmX".equals(tagName)) {
						tmpLongitude = Double.valueOf(parser.getText());
					}
					if ("tmY".equals(tagName)) {
						tmpLatitude = Double.valueOf(parser.getText());
						setBusMarker(tmparsId, tmpstNm, tmpLongitude, tmpLatitude, (Integer) mMapView.getTag());
						mMapView.setTag((Integer) mMapView.getTag() + 1);

						if (tmpLongitude < minLongitude) {
							minLongitude = tmpLongitude;
						};
						if (tmpLatitude < minLatitude) {
							minLatitude = tmpLatitude;
						};

						if (tmpLongitude > maxLongitude) {
							maxLongitude = tmpLongitude;
						};
						if (tmpLatitude > maxLatitude) {
							maxLatitude = tmpLatitude;
						};
					}

					break;
				}

				parserEvent = parser.next();
			}

			if (parserEvent == XmlPullParser.END_DOCUMENT) {
				double Lon = maxLongitude - ((maxLongitude - minLongitude) / 2f); // x��
				double Lat = maxLatitude - ((maxLatitude - minLatitude) / 2f); // y��
				// double Lon = ((maxLongitude - minLongitude) / 2f); // x��
				// double Lat = ((maxLatitude - minLatitude) / 2f); // y��

				mLongitude = Lon;
				mLatitude = Lat;
				mMapView.setLocationPoint(mLongitude, mLatitude);
				mMapView.setCenterPoint(mLongitude, mLatitude);

				for (int i = 19; i > 1; i--) {
					mMapView.setZoomLevel(i);
					TMapPoint TopPnt = mMapView.convertPointToGps(0, 0);

					double PntLon = mLongitude - TopPnt.getLongitude();
					double PntLat = TopPnt.getLatitude() - mLatitude;

					if (minLongitude > TopPnt.getLongitude() && minLatitude > mLatitude - PntLat) {
						if (maxLongitude < mLongitude + PntLon && maxLatitude < TopPnt.getLatitude()) {
							mMapView.setZoomLevel(i);
							break;
						}
					}
				}

			}

		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
	}

	@Override
	protected String doInBackground(String... arg0) {
		String result = "결과가 없습니다.";
		SeoulBusApiController sbac = new SeoulBusApiController("");

		try {
			if ("getStationByName".equals(arg0[0])) {
				result = sbac.getStationByName(arg0[1]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;

	}

	public void onLocationChange(Location location) {
	}

	public void setBusMarker(String id, String name, double longitude, double latitude, Integer tag) {
		TMapPoint tpoint = new TMapPoint(latitude, longitude);
		TMapMarkerItem tItem = new TMapMarkerItem();
		tItem.setTMapPoint(tpoint);
		tItem.setName(id);
		tItem.setVisible(tItem.VISIBLE);
		tItem.setCanShowCallout(true);
		tItem.setCalloutTitle(name);
		tItem.setCalloutSubTitle(id);

		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.map_pin_red);
		tItem.setIcon(bitmap);

		Bitmap bitmap2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.stat_notify_bus);
		tItem.setCalloutLeftImage(bitmap2);

		mMapView.addMarkerItem(tag.toString(), tItem);

		// mMapView.setLocationPoint(longitude, latitude);
	}

}